﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Bricks.Business.Service.Impl;
using Bricks.Site.Models;
using Bricks.Business.Models.FlowProcess;
using System.Xml;
using System.Web.Script.Serialization;
using Bricks.Business.Service;
using Bricks.Component.Utils;
using Bricks.Site.Web.CommonUtils;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models.Contract;
using Bricks.Component.Data;
using Bricks.Site.Models.DBViewModel.Contract;
using System.Text;
using Bricks.Business.Models.Account;
using Bricks.Business.Models.ProjectContract;
using System.Configuration;
using Bricks.Business.Service.CommonSupport;
using Bricks.Site.Models.DBViewModel.Expense;

namespace Bricks.Site.Web.Controllers
{
    [Export]
    public class ContractInfoController : BaseController
    {
        #region 属性
        [Import]
        public IContractInfoService ContractInfoService { get; set; }
        [Import]
        public ICommonContractInfoService CommonContractInfoService { get; set; }
        [Import]
        public IOrgInfoService OrgInfoService { get; set; }
        [Import]
        public IProjectInfoService ProjectInfoService { get; set; }
        [Import]
        public IDocumentService DocumentService { get; set; }
        [Import]
        public IUserOrgService UserOrgService { get; set; }
        #endregion

        #region 流程用到的合同筛选
        public class ContractInfoTemp
        {
            public Guid ProjectID { get; set; }

            public string ProjectName { get; set; }

            public Guid ID { get; set; }

            public string ContractName { get; set; }
        }

        //获取施工合同信息，用在变更申请和变更令的合同选择
        public ActionResult ContractInfoList(string correspondenceUnitCode)
        {
            List<ContractInfoTemp> lstContractInfoTemp = new List<ContractInfoTemp>();
            OrgInfo orgInfo = OrgInfoService.Orgs.SingleOrDefault(o => o.OrgCode == correspondenceUnitCode);
            if (orgInfo != null)
            {
                string correspondenceUnitStr = "'" + orgInfo.ID.ToString() + "',";
                FlowFilterAndRequestUtils.GetSubCorrespondenceUnit(orgInfo.ID, ref correspondenceUnitStr);
                string sql = "select * from V_ContractInfoes where CorrespondenceUnit in (" + correspondenceUnitStr.Trim(',') + ") ORDER BY LevelCode";
                var listView = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql);
                foreach (VMContractInfo vmContractInfo in listView)
                {
                    ProjectInfo projectInfo = ProjectInfoService.ProjectInfoes.SingleOrDefault(p => p.ID == vmContractInfo.PID);
                    if (projectInfo != null)
                    {
                        lstContractInfoTemp.Add(new ContractInfoTemp() { ProjectID = vmContractInfo.PID, ProjectName = projectInfo.ProjectName, ID = vmContractInfo.ID, ContractName = vmContractInfo.ContractName });
                    }
                }
            }
            return Json(lstContractInfoTemp, JsonRequestBehavior.AllowGet);
        }

        //用在进度管理里面
        public ActionResult ContractInfoListByProjectIDAndType(string projectID, string contractType)
        {
            Guid guidProjectID = GuidHelper.NewGuid();
            if (!string.IsNullOrEmpty(projectID))
            {
                guidProjectID = projectID.ToGuid();
            }
            string sql = "select * from V_ContractInfoes where PID ='" + guidProjectID + "' and ContractType='" + contractType + "' ORDER BY LevelCode";

            //如果当前用户不是超级管理员且不在能查看合同的部门列表里面，则需要对登陆用户的有流程的单据列表进行筛选：获取需要做合同筛选的顶级部门，只能查看登陆用户所属部门或者子部门与客户端合同对应单位相同的那些

            //获取登陆用户的机构信息
            List<OrgInfo> orgs = (from u in UserInfoService.Users
                                  join uo in UserOrgService.UserOrgs on u.ID equals uo.UserID
                                  join o in OrgInfoService.Orgs on uo.OrgID equals o.ID
                                  where u.UserName == User.Identity.Name
                                  select o).ToList();
            if (orgs.Count() > 0 && SystemData.Instance.CurrentUser.UserType == UserType.Common && !FlowFilterAndRequestUtils.IsContainLoginOrg(orgs))
            {
                string topDepartmentOfNeedFilterContractStr = ConfigurationManager.AppSettings["TopDepartmentOfNeedFilterContract"] as string;
                if (!string.IsNullOrEmpty(topDepartmentOfNeedFilterContractStr))
                {
                    //获取能新增客户端合同的所有部门
                    List<Guid> lstAllAddConstructionContractDepartment = new List<Guid>();
                    string[] addConstructionContractTopDepartmentArr = topDepartmentOfNeedFilterContractStr.Split(',');
                    foreach (string addConstructionContractTopDepartment in addConstructionContractTopDepartmentArr)
                    {
                        OrgInfo orgInfo = OrgInfoService.Orgs.SingleOrDefault(o => o.OrgCode == addConstructionContractTopDepartment);
                        if (orgInfo != null)
                        {
                            lstAllAddConstructionContractDepartment.Add(orgInfo.ID);
                            FlowFilterAndRequestUtils.GetSubOrgInfo(orgInfo.ID, ref lstAllAddConstructionContractDepartment);
                        }
                    }

                    //如果所有能新增客户端合同的机构包含登陆用户所在部门，则需要筛选数据
                    if (FlowFilterAndRequestUtils.IsContainLoginOrg(lstAllAddConstructionContractDepartment, orgs))
                    {
                        string correspondenceUnitStr = string.Empty;
                        foreach (var org in orgs)
                        {
                            correspondenceUnitStr += "'" + org.ID + "',";
                            FlowFilterAndRequestUtils.GetSubCorrespondenceUnit(org.ID, ref correspondenceUnitStr);
                        }
                        sql = "select * from V_ContractInfoes where PID ='" + guidProjectID + "' and ContractType='" + contractType + "'and CorrespondenceUnit in (" + correspondenceUnitStr.Trim(',') + ") ORDER BY LevelCode ";
                    }
                }
            }
            var listView = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql);
            return Json(listView, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ContractInfoListByProjectID(string projectID)
        {
            var listView = ContractInfoListByProjectIDForFlow(projectID);
            return Json(listView, JsonRequestBehavior.AllowGet);
        }

        private List<VMContractInfo> ContractInfoListByProjectIDForFlow(string projectID)
        {
            Guid guidProjectID = GuidHelper.NewGuid();
            if (!string.IsNullOrEmpty(projectID))
            {
                guidProjectID = projectID.ToGuid();
            }
            string sql = "select * from V_ContractInfoes where PID ='" + guidProjectID + "'  ORDER BY LevelCode";

            //如果当前用户不是超级管理员且不在能查看合同的部门列表里面，则需要对登陆用户的有流程的单据列表进行筛选：获取需要做合同筛选的顶级部门，只能查看登陆用户所属部门或者子部门与客户端合同对应单位相同的那些

            //获取登陆用户的机构信息
            List<OrgInfo> orgs = (from u in UserInfoService.Users
                                  join uo in UserOrgService.UserOrgs on u.ID equals uo.UserID
                                  join o in OrgInfoService.Orgs on uo.OrgID equals o.ID
                                  where u.UserName == User.Identity.Name
                                  select o).ToList();
            if (orgs.Count() > 0 && SystemData.Instance.CurrentUser.UserType == UserType.Common && !FlowFilterAndRequestUtils.IsContainLoginOrg(orgs))
            {
                string topDepartmentOfNeedFilterContractStr = ConfigurationManager.AppSettings["TopDepartmentOfNeedFilterContract"] as string;
                if (!string.IsNullOrEmpty(topDepartmentOfNeedFilterContractStr))
                {
                    //获取能新增客户端合同的所有部门
                    List<Guid> lstAllAddConstructionContractDepartment = new List<Guid>();
                    string[] addConstructionContractTopDepartmentArr = topDepartmentOfNeedFilterContractStr.Split(',');
                    foreach (string addConstructionContractTopDepartment in addConstructionContractTopDepartmentArr)
                    {
                        OrgInfo orgInfo = OrgInfoService.Orgs.SingleOrDefault(o => o.OrgCode == addConstructionContractTopDepartment);
                        if (orgInfo != null)
                        {
                            lstAllAddConstructionContractDepartment.Add(orgInfo.ID);
                            FlowFilterAndRequestUtils.GetSubOrgInfo(orgInfo.ID, ref lstAllAddConstructionContractDepartment);
                        }
                    }

                    //如果所有能新增客户端合同的机构包含登陆用户所在部门，则需要筛选数据
                    if (FlowFilterAndRequestUtils.IsContainLoginOrg(lstAllAddConstructionContractDepartment, orgs))
                    {
                        string correspondenceUnitStr = string.Empty;
                        foreach (var org in orgs)
                        {
                            correspondenceUnitStr += "'" + org.ID + "',";
                            FlowFilterAndRequestUtils.GetSubCorrespondenceUnit(org.ID, ref correspondenceUnitStr);
                        }
                        sql = "select * from V_ContractInfoes where PID ='" + guidProjectID + "' and CorrespondenceUnit in (" + correspondenceUnitStr.Trim(',') + ") ORDER BY LevelCode ";
                    }
                }
            }
            return DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql);
        }
        #endregion


        public ActionResult AllContractInfoList()
        {
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        public ActionResult GetAllContractInfoList(string pid)
        {
            Guid projectID = pid.ToGuid();
            Guid constructionID = Guid.NewGuid();
            Guid commonID = Guid.NewGuid();
            List<ContractInfoView> lstContractInfoView = new List<ContractInfoView>();
            lstContractInfoView.Add(new ContractInfoView()
            {
                ID = constructionID,
                PID = projectID,
                ContractName = "施工类",
                DisplayPID = Guid.NewGuid(),
                ContractSource = ""
            });
            lstContractInfoView.Add(new ContractInfoView()
            {
                ID = commonID,
                PID = projectID,
                ContractName = "其他类",
                DisplayPID = Guid.NewGuid(),
                ContractSource = ""
            });

            if (!String.IsNullOrEmpty(pid))
            {
                var listView = ContractInfoListByProjectIDForFlow(pid);
                if (listView.Count > 0)
                {
                    VMContractInfo vmContractInfoTotal = new VMContractInfo();
                    vmContractInfoTotal.ID = GuidHelper.NewGuid();
                    vmContractInfoTotal.PID = projectID;
                    vmContractInfoTotal.ContractUnitName = "";
                    vmContractInfoTotal.ContractCode = "*****合计*****";
                    vmContractInfoTotal.ContractName = "合计";
                    vmContractInfoTotal.ContractMoney = 0;
                    vmContractInfoTotal.ConstructionDrawMoney = 0;
                    vmContractInfoTotal.AlterIncreaseOrDecreaseMoney = 0;
                    vmContractInfoTotal.AfterAlterMoney = 0;
                    vmContractInfoTotal.AccumulativeEstimateMoney = 0;
                    foreach (VMContractInfo vmContractInfo in listView)
                    {
                        vmContractInfoTotal.ContractMoney += vmContractInfo.ContractMoney;
                        vmContractInfoTotal.ConstructionDrawMoney += vmContractInfo.ConstructionDrawMoney;
                        vmContractInfoTotal.AlterIncreaseOrDecreaseMoney += vmContractInfo.AlterIncreaseOrDecreaseMoney;
                        vmContractInfoTotal.AfterAlterMoney += vmContractInfo.AfterAlterMoney;
                        vmContractInfoTotal.AccumulativeEstimateMoney += vmContractInfo.AccumulativeEstimateMoney;
                    }
                    vmContractInfoTotal.AccumulativeEstimateProportion = vmContractInfoTotal.AccumulativeEstimateMoney / vmContractInfoTotal.AfterAlterMoney;
                    listView.Add(vmContractInfoTotal);
                }
                var contractInfos = (from c in listView
                                     select new ContractInfoView
                                     {
                                         ID = c.ID,
                                         PID = c.PID,
                                         ContractUnitName = c.ContractUnitName,
                                         ContractCode = c.ContractCode,
                                         ContractName = c.ContractName,
                                         ContractMoney = c.ContractMoney,
                                         ConstructionDrawMoney = c.ConstructionDrawMoney,
                                         AlterIncreaseOrDecreaseMoney = c.AlterIncreaseOrDecreaseMoney,
                                         AfterAlterMoney = c.AfterAlterMoney,
                                         AccumulativeEstimateMoney = c.AccumulativeEstimateMoney,
                                         AccumulativeEstimateProportion = c.AccumulativeEstimateProportion == null ? "0%" : Math.Round(Convert.ToDecimal(c.AccumulativeEstimateProportion * 100), 2).ToString() + "%",
                                         DisplayPID = constructionID,
                                         ContractSource = "施工类"
                                     }).Concat(from c in CommonContractInfoService.CommonContractInfos
                                               where c.PID == projectID
                                               select new ContractInfoView
                                               {
                                                   ID = c.ID,
                                                   PID = c.PID,
                                                   ContractUnitName = c.ContractUnitName,
                                                   ContractCode = c.ContractCode,
                                                   ContractName = c.ContractName,
                                                   ContractMoney = c.ContractMoney,
                                                   ConstructionDrawMoney = c.ContractMoney,
                                                   AlterIncreaseOrDecreaseMoney = 0,
                                                   AfterAlterMoney = c.ContractMoney,
                                                   AccumulativeEstimateMoney = 0,
                                                   AccumulativeEstimateProportion = "0%",
                                                   DisplayPID = commonID,
                                                   ContractSource = "其他类"
                                               });
                foreach (var c in contractInfos)
                {
                    lstContractInfoView.Add(new ContractInfoView()
                    {
                        ID = c.ID,
                        PID = c.PID,
                        ContractUnitName = c.ContractUnitName,
                        ContractCode = c.ContractCode,
                        ContractName = c.ContractName,
                        ContractMoney = c.ContractMoney,
                        ConstructionDrawMoney = c.ConstructionDrawMoney,
                        AlterIncreaseOrDecreaseMoney = c.AlterIncreaseOrDecreaseMoney,
                        AfterAlterMoney = c.AfterAlterMoney,
                        AccumulativeEstimateMoney = c.AccumulativeEstimateMoney,
                        AccumulativeEstimateProportion = c.AccumulativeEstimateProportion,
                        DisplayPID = c.DisplayPID,
                        ContractSource = c.ContractSource
                    });
                }
            }
            return Json(lstContractInfoView, JsonRequestBehavior.AllowGet);
        }



        public ActionResult GetCommonContractInfo(string id, string pid)
        {
            Guid guidID;
            if (!String.IsNullOrEmpty(id))
            {
                guidID = id.ToGuid();
            }
            else
            {
                guidID = Guid.NewGuid();
            }

            ContractInfoView model = CommonContractInfoService.GetCommonContractInfo(guidID);
            if (model == null)
            {
                model = new ContractInfoView();
                model.ID = guidID;
                model.PID = pid.ToGuid();
            }
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveCommonContractInfo(ContractInfoView model)
        {
            return Json(CommonContractInfoService.SaveCommonContractInfo(model), "text/html");
        }

        public ActionResult Delete(string id)
        {
            Guid guidID = id.ToGuid();
            var exeResult = CommonContractInfoService.Delete(guidID);
            if (exeResult.ResultType == OperationResultType.Success)
            {
                var docDeleteResult = DocumentService.DeleteByInstanceID(guidID);
                if (docDeleteResult == true)
                {
                    exeResult.Message += "，已删除关联附件记录";
                }
            }
            return Json(exeResult);
        }

        public ActionResult PreviewCommonContractInfo(string id)
        {
            ContractInfoView model = CommonContractInfoService.GetCommonContractInfo(id.ToGuid());
            return View(model);
        }



        public ActionResult GetContractInfo(string id)
        {
            //ContractInfoView model = ContractInfoService.GetContractInfo(id.ToGuid());
            string sql = "select * from V_ContractInfoes where id='" + id + "'";
            VMContractInfo model = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql)[0];
            model.ContractMoneyStr = model.ContractMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.ContractMoney), 0));
            model.ConstructionDrawMoneyStr = model.ConstructionDrawMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.ConstructionDrawMoney), 0));
            model.AlterIncreaseOrDecreaseMoneyStr = model.AlterIncreaseOrDecreaseMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AlterIncreaseOrDecreaseMoney), 0));
            model.AfterAlterMoneyStr = model.AfterAlterMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AfterAlterMoney), 0));
            model.AccumulativeEstimateMoneyStr = model.AccumulativeEstimateMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AccumulativeEstimateMoney), 0));
            model.AccumulativeEstimateProportionStr = model.AccumulativeEstimateProportion == null ? "0%" : Math.Round(Convert.ToDecimal(model.AccumulativeEstimateProportion * 100), 2).ToString() + "%";
            return View(model);
        }

        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult SaveContractInfo(ContractInfoView model)
        //{
        //    return Json(ContractInfoService.ModifyContractInfo(model), "text/html");
        //}

        public ActionResult PreviewContractInfo(string id)
        {
            //ContractInfoView model = ContractInfoService.GetContractInfo(id.ToGuid());
            string sql = "select * from V_ContractInfoes where id='" + id + "'";
            VMContractInfo model = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql)[0];
            model.ContractMoneyStr = model.ContractMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.ContractMoney), 0));
            model.ConstructionDrawMoneyStr = model.ConstructionDrawMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.ConstructionDrawMoney), 0));
            model.AlterIncreaseOrDecreaseMoneyStr = model.AlterIncreaseOrDecreaseMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AlterIncreaseOrDecreaseMoney), 0));
            model.AfterAlterMoneyStr = model.AfterAlterMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AfterAlterMoney), 0));
            model.AccumulativeEstimateMoneyStr = model.AccumulativeEstimateMoney == null ? 0 : Convert.ToInt32(Math.Round(Convert.ToDecimal(model.AccumulativeEstimateMoney), 0));
            model.AccumulativeEstimateProportionStr = model.AccumulativeEstimateProportion == null ? "0.00%" : Math.Round(Convert.ToDecimal(model.AccumulativeEstimateProportion * 100), 2).ToString() + "%";
            return View(model);
        }

        public ActionResult GetConstructionContractEstimateList(string contractID)
        {
            List<VMConstructionContractMeasurementPeriod> lstVMConstructionContractMeasurementPeriod = new List<VMConstructionContractMeasurementPeriod>();
            string sql = "select * from StartAdvancePayment where ContractID='" + contractID + "'";
            var lstStartAdvancePayment = DbSqlHelper<StartAdvancePayment>.SqlQueryCommon(sql);
            foreach (StartAdvancePayment startAdvancePayment in lstStartAdvancePayment)
            {
                lstVMConstructionContractMeasurementPeriod.Add(new VMConstructionContractMeasurementPeriod()
                {
                    ID = GuidHelper.NewGuid(),
                    Type = 0,
                    EndDate = startAdvancePayment.PayTime == null ? "" : Convert.ToDateTime(startAdvancePayment.PayTime).ToString("yyyyMMdd"),
                    ContractStages = "开工预付款",
                    Total = startAdvancePayment.PayMoney == null ? 0 : startAdvancePayment.PayMoney
                });
            }

            sql = @"SELECT  1 AS Type,
                            CONVERT(uniqueidentifier, a.ID) AS ID,
		                    CASE ISNULL(A.JSRQ,'') WHEN '' THEN '' ELSE CONVERT(VARCHAR(8),A.JSRQ,112) END AS EndDate,  
                            A.QCID AS ContractStagesNum,
		                    '第'+A.QCID+'期' AS ContractStages, 
		                    ISNULL(B.hj,0.00) AS Total,
		                    ISNULL(B.bzzlj,0.00) AS BehindTheGold,
		                    ISNULL(B.zxzlj,0.00) AS SpecialBehindTheGold,
		                    0.00 AS PrepaymentSQM,
		                    ISNULL(C.BQKCDYYFK,0.00) AS PrepaymentBQ,
		                    0.00 AS TaxSQM,
		                    ISNULL(C.KSJ,0.00) AS TaxBQ,
		                    0.00 AS RetentionMoneySQM,
		                    ISNULL(C.KBLJ,0.00) AS RetentionMoneyBQ,
		                    0.00 AS MigrantWorkersProtectionSQM,
		                    ISNULL(C.KHGZ,0.00) AS MigrantWorkersProtectionBQ,
		                    0.00 AS PenaltySQM,
		                    ISNULL(C.WYFJ,0.00) AS PenaltyBQ,
		                    ISNULL(C.SJZFJE,0.00) AS ActualPayment,
		                    ISNULL(D.hj,0.00) AS CumulativePayment
                    FROM XMQC AS A
                    LEFT OUTER JOIN (SELECT BDID,QCID,hj,bzzlj,zxzlj FROM REP_ZQJKZF1 WHERE jllx=9) AS B
                    ON A.BDID=B.BDID AND A.QCID=B.QCID
                    LEFT OUTER JOIN (SELECT BDID,QCID,BQKCDYYFK,KSJ,KBLJ,KHGZ,WYFJ,SJZFJE FROM REP_ZQJKZF2 WHERE jllx=0) AS C
                    ON A.BDID=C.BDID AND A.QCID=C.QCID
                    LEFT OUTER JOIN (SELECT BDID,QCID,hj FROM REP_ZQJKZF1 WHERE jllx=8) AS D
                    ON A.BDID=D.BDID AND A.QCID=D.QCID
                    where A.BDID='" + contractID + @"'
                    ORDER BY A.JSRQ";

            var lstCut = DbSqlHelper<VMConstructionContractMeasurementPeriod>.SqlQueryCommon(sql);
            foreach (VMConstructionContractMeasurementPeriod item in lstCut)
            {
                if (item.ContractStagesNum != "1")
                {
                    try
                    {
                        int contractStages = Convert.ToInt32(item.ContractStagesNum) - 1;
                        sql = @"select ft.ID as ID,ft.BDID as SectionID,ft.QCID as PeriodID,'LeftName' as LeftName,'RightName' as RightName,
                                ft.BQKCDYYFK as CutPaymentForPerson,ft.KHJG as CutPaymentForMaterial,ft.KSJ as CutPaymentForTaxation,ft.KBLJ as CutPaymentForSave,
                                ft.KHGZ as CutPaymentForSalary,ft.WYFJ as CutPaymentForPenalty,ft.KKHJ as CutPaymentForTotal,ft.SJZFJE as CutPaymentForReality
                                from REP_ZQJKZF2 as ft where bdid='" + contractID + @"' and qcid='" + contractStages + "' and jllx=1";
                        List<VMExpenseFirstCutPayment> result = DbSqlHelper<VMExpenseFirstCutPayment>.SqlQueryCommon(sql);
                        if (result.Count == 1)
                        {
                            item.PrepaymentSQM = result[0].CutPaymentForPerson == null ? 0 : result[0].CutPaymentForPerson;
                            item.TaxSQM = result[0].CutPaymentForTaxation == null ? 0 : result[0].CutPaymentForTaxation;
                            item.RetentionMoneySQM = result[0].CutPaymentForSave == null ? 0 : result[0].CutPaymentForSave;
                            item.MigrantWorkersProtectionSQM = result[0].CutPaymentForSalary == null ? 0 : result[0].CutPaymentForSalary;
                            item.PenaltySQM = result[0].CutPaymentForPenalty == null ? 0 : result[0].CutPaymentForPenalty;
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            lstVMConstructionContractMeasurementPeriod.AddRange(lstCut);

            return Json(lstVMConstructionContractMeasurementPeriod, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetContractBillInfoList(string contractID)
        {
            string sql = "select * from V_ContractBillInfoes where ContractID='" + contractID + "' and ID not in (select id from V_ContractBillInfoes as a where ISNULL(money,0)=0 and ISNULL(ConstructionDrawMoney,0)=0 and (select COUNT(1) from V_ContractBillInfoes where ISNULL(PID,'-1')<>'-1' and Convert(nvarchar(100),PID)=Convert(nvarchar(100),a.ID))=0 and ContractID='" + contractID + "') order by BillCode";
            var lstBill = DbSqlHelper<VMContractBillInfoes>.SqlQueryCommon(sql);

            sql = "select DISTINCT PID from V_ContractBillInfoes as a where ISNULL(money,0)=0 and ISNULL(ConstructionDrawMoney,0)=0 and (select COUNT(1) from V_ContractBillInfoes where ISNULL(PID,'-1')<>'-1' and Convert(nvarchar(100),PID)=Convert(nvarchar(100),a.ID))=0 and ContractID='" + contractID + "'";
            var lstPID = DbSqlHelper<VMContractBillInfoesOnlyPID>.SqlQueryCommon(sql);

            List<string> lstParentPID = new List<string>();
            foreach (VMContractBillInfoesOnlyPID VMContractBillInfoesOnlyPID in lstPID)
            {
                if (VMContractBillInfoesOnlyPID.PID != "-1")
                {
                    VMContractBillInfoes item = lstBill.SingleOrDefault(l => l.ID == VMContractBillInfoesOnlyPID.PID.ToGuid());
                    List<VMContractBillInfoes> lstSubItem = lstBill.Where(l => l.PID == VMContractBillInfoesOnlyPID.PID).ToList();
                    if (item != null)
                    {
                        if (!lstParentPID.Contains(item.PID))
                        {
                            lstParentPID.Add(item.PID);
                        }
                        if ((item.Money == null || item.Money == 0) && (item.ConstructionDrawMoney == null || item.ConstructionDrawMoney == 0) && lstSubItem.Count == 0)
                        {
                            lstBill.Remove(item);
                        }
                    }
                }
            }
            if (lstParentPID.Count > 0)
            {
                RemoveContractBillInfoList(lstBill, lstParentPID);
            }

            return Json(lstBill, JsonRequestBehavior.AllowGet);
        }

        private void RemoveContractBillInfoList(List<VMContractBillInfoes> lstBill, List<string> lstPID)
        {
            List<string> lstParentPID = new List<string>();
            foreach (string pid in lstPID)
            {
                if (pid != "-1")
                {
                    VMContractBillInfoes item = lstBill.SingleOrDefault(l => l.ID == pid.ToGuid());
                    List<VMContractBillInfoes> lstSubItem = lstBill.Where(l => l.PID == pid).ToList();
                    if (item != null)
                    {
                        lstParentPID.Add(item.PID);
                        if ((item.Money == null || item.Money == 0) && (item.ConstructionDrawMoney == null || item.ConstructionDrawMoney == 0) && lstSubItem.Count == 0)
                        {
                            lstBill.Remove(item);
                        }
                    }
                }
            }
            if (lstParentPID.Count > 0)
            {
                RemoveContractBillInfoList(lstBill, lstParentPID);
            }
        }

        public ActionResult GetContractBillInfoListForAlterOrder(string contractID)
        {
            string sql = "select * from V_ContractBillInfoes where ContractID='" + contractID + "' order by BillCode";
            var lstBill = DbSqlHelper<VMContractBillInfoes>.SqlQueryCommon(sql);

            if (!string.IsNullOrEmpty(contractID))
            {
                sql = "SELECT * FROM AlterOrderBills WHERE PID IN (SELECT ID FROM AlterOrders WHERE ContractID='" + contractID + "') and BillCode not in (select BillCode from V_ContractBillInfoes where ContractID='" + contractID + "' ) ORDER BY BillCode";
                var lstBGLBill = DbSqlHelper<AlterOrderBillView>.SqlQueryCommon(sql);
                if (lstBGLBill != null && lstBGLBill.Count > 0)
                {
                    Guid id = Guid.NewGuid();
                    lstBill.Add(new VMContractBillInfoes() { ID = id, PID = "-1", ContractID = contractID, BillCode = "BGLQD", BillName = "变更令清单" });
                    foreach (var item in lstBGLBill)
                    {
                        var list= lstBill.Where(l => l.BillCode == item.BillCode);
                        if (list != null && list.Count() > 0)
                        {
                            continue;
                        }
                        else
                        {
                            decimal? price = 0;
                            if (item.Price != null)
                            {
                                price = Convert.ToDecimal(item.Price);
                            }
                            lstBill.Add(new VMContractBillInfoes() { ID = item.ID, PID = id.ToString(), ContractID = contractID, BillCode = item.BillCode, BillName = item.BillName, Unit = item.Unit, Price = price });
                        }
                    }
                }
            }
            return Json(lstBill, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ConstructionContractEstimateBillList(string contractID, string contractStagesID)
        {
            VMConstructionContractEstimates vmConstructionContractEstimates = new VMConstructionContractEstimates();
            vmConstructionContractEstimates.ContractID = contractID.ToGuid();
            vmConstructionContractEstimates.ID = contractStagesID.ToGuid();
            return View(vmConstructionContractEstimates);
        }

        public ActionResult GetConstructionContractStagesList(string contractID)
        {
            string sql = "select ID,ContractStages from V_ConstructionContractEstimates where ContractID='" + contractID + "' order by ContractStages";
            var listView = DbSqlHelper<VMConstructionContractEstimates>.SqlQueryCommon(sql);
            return Json(listView, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetConstructionContractEstimateBillList(string contractStagesID)
        {
            string sql = "select * from V_ConstructionContractEstimateBills where ContractStagesID='" + contractStagesID + "' order by BillCode";
            var listView = DbSqlHelper<VMConstructionContractEstimateBills>.SqlQueryCommon(sql);

            return Json(listView, JsonRequestBehavior.AllowGet);
        }


        #region 选择合同相关代码（Add By Luozx 2014-04-28）
        /// <summary>
        /// 选择合同
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseContract()
        {
            return View();
        }

        /// <summary>
        /// 选择合同Post
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseContractPost()
        {
            OperationResult result = new OperationResult(OperationResultType.Success, "选择成功");
            return Json(result);
        }

        /// <summary>
        /// 获取合同类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetContractType()
        {
            List<ContractType> result = new List<ContractType>();
            result.Add(new ContractType() { TypeName = "施工类" });
            result.Add(new ContractType() { TypeName = "其他类" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 合同类型结构（供上方的获取类型使用）
        /// </summary>
        public class ContractType
        {
            /// <summary>
            /// 类型名称
            /// </summary>
            public string TypeName { get; set; }
        }

        /// <summary>
        /// 获取指定类型的合同列表
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="typeName"></param>
        /// <param name="ids">选中的合同</param>
        /// <returns></returns>
        public ActionResult GetTypeContractList(string pid, string typeName, string ids)
        {
            Guid guPid = pid.ToGuid();
            switch (typeName)
            {
                case "施工类":
                    var contractList = (from m in ContractInfoService.ContractInfos
                                        where m.PID == guPid
                                        select new ContractView
                                        {
                                            IsChecked = false,
                                            ID = m.ID,
                                            PID = m.PID,
                                            ContractName = m.ContractName
                                        }).ToList();
                    if (!String.IsNullOrEmpty(ids))
                    {
                        foreach (var item in contractList)
                        {
                            if (ids.Contains(item.ID.ToString()))
                            {
                                item.IsChecked = true;
                            }
                        }
                    }
                    return Json(contractList, JsonRequestBehavior.AllowGet);
                case "其他类":
                    var commonContractList = (from m in CommonContractInfoService.CommonContractInfos
                                              where m.PID == guPid
                                              select new ContractView
                                              {
                                                  IsChecked = false,
                                                  ID = m.ID,
                                                  PID = m.PID,
                                                  ContractName = m.ContractName
                                              }).ToList();
                    if (!String.IsNullOrEmpty(ids))
                    {
                        foreach (var item in commonContractList)
                        {
                            if (ids.Contains(item.ID.ToString()))
                            {
                                item.IsChecked = true;
                            }
                        }
                    }
                    return Json(commonContractList, JsonRequestBehavior.AllowGet);

                default:
                    return null;
            }
        }

        /// <summary>
        /// 获取完整的合同名称（项目-类型-名称）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public string GetFullContractNameByID(string ids)
        {
            string result = string.Empty;
            if (!String.IsNullOrEmpty(ids))
            {
                string[] idArray = ids.Split(',');
                if (idArray != null && idArray.Length > 0)
                {
                    List<Guid> guids = new List<Guid>();
                    foreach (string id in idArray)
                    {
                        guids.Add(id.ToGuid());
                    }
                    result = ContractInfoService.GetFullContractNameByID(guids);
                }
            }
            return result;
        }
        #endregion
    }
}